package com.moyun.modelclass.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.SpanUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.moyun.modelclass.adapter.VipAdapter;
import com.moyun.modelclass.base.BaseActivity;
import com.moyun.modelclass.dialog.CashierDialog;
import com.moyun.modelclass.http.CommonConfiguration;
import com.moyun.modelclass.http.api.MemberSettingApi;
import com.moyun.modelclass.http.api.OrderInfoApi;
import com.moyun.modelclass.http.api.PayParamsApi;
import com.moyun.modelclass.http.api.VipOrderCreateApi;
import com.moyun.modelclass.http.model.HttpData;
import com.moyun.modelclass.listener.PayResult;
import com.moyun.modelclass.listener.RecyclerItemClickListener;
import com.moyun.modelclass.R;
import com.moyun.modelclass.utils.StatusBarUtil;

import java.util.Map;

/**
 * 作者：Meteor
 * tip：会员中心
 */
public class VipActivity extends BaseActivity implements VipAdapter.OnItemSelectedChangedListener {
    private RelativeLayout rlVipTop;
    private ImageView ivVipBack;
    private RecyclerView rvVipRecycler;
    private TextView tvVipAgreement;
    private TextView tvVipTipTileOne;
    private TextView tvVipTipContentOne;
    private ImageView ivVipTipImageOne;
    private TextView tvVipTipTileTwo;
    private TextView tvVipTipContentTwo;
    private ImageView ivVipTipImageTwo;
    private RelativeLayout rlVipTipTileThree;
    private TextView tvVipTipTileThree;
    private TextView tvVipTipContentThree;
    private ImageView ivVipTipImageThree;
    private TextView tvVipBuy;

    private VipAdapter vipAdapter = new VipAdapter();
    private MemberSettingApi.BeanInfo mBeanInfo = null;//获取会员信息描述，会员种类
    private int mCurrentLevel = 1;//当前等级

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message msg) {
            //对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
            @SuppressWarnings("unchecked")
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            // 判断resultStatus 为9000则代表支付成功
            if (TextUtils.equals(payResult.getResultStatus(), "9000")) {
                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                ToastUtils.showShort("支付成功" + payResult.getMemo());
                initMemberSetting();
            } else {
                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                ToastUtils.showShort("支付失败" + payResult.getMemo());
            }
        }
    };

    public static void start(Context context) {
        Intent starter = new Intent(context, VipActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_vip;
    }

    @Override
    protected void assignViews() {
        rlVipTop = (RelativeLayout) findViewById(R.id.rl_vip_top);
        ivVipBack = (ImageView) findViewById(R.id.iv_vip_back);
        rvVipRecycler = (RecyclerView) findViewById(R.id.rv_vip_recycler);
        tvVipAgreement = (TextView) findViewById(R.id.tv_vip_agreement);

        tvVipTipTileOne = (TextView) findViewById(R.id.tv_vip_tip_tile_one);
        tvVipTipContentOne = (TextView) findViewById(R.id.tv_vip_tip_content_one);
        ivVipTipImageOne = (ImageView) findViewById(R.id.iv_vip_tip_image_one);
        tvVipTipTileTwo = (TextView) findViewById(R.id.tv_vip_tip_tile_two);
        tvVipTipContentTwo = (TextView) findViewById(R.id.tv_vip_tip_content_two);
        ivVipTipImageTwo = (ImageView) findViewById(R.id.iv_vip_tip_image_two);
        rlVipTipTileThree = (RelativeLayout) findViewById(R.id.rl_vip_tip_tile_three);
        tvVipTipTileThree = (TextView) findViewById(R.id.tv_vip_tip_tile_three);
        tvVipTipContentThree = (TextView) findViewById(R.id.tv_vip_tip_content_three);
        ivVipTipImageThree = (ImageView) findViewById(R.id.iv_vip_tip_image_three);

        tvVipBuy = (TextView) findViewById(R.id.tv_vip_buy);
        StatusBarUtil.setPaddingSmart(this, rlVipTop);

        rvVipRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        vipAdapter.setOnItemSelectedChangedListener(this);
        rvVipRecycler.setAdapter(vipAdapter);

        tvVipAgreement.setMovementMethod(LinkMovementMethod.getInstance());
        SpanUtils.with(tvVipAgreement)
                .append("开通前请阅读")
                .append("《会员服务协议》")
                .setSpans(new ClickableSpan() {
                    @Override
                    public void onClick(@NonNull View widget) {
                        WebRichActivity.start(mActivity, "MembershipServiceAgreement");
                    }

                    @Override
                    public void updateDrawState(TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setColor(Color.parseColor("#FF6600")); // 设置你想要的颜色
                        ds.setUnderlineText(false); // 如果需要的话，取消下划线
                    }
                }).create();
    }

    @Override
    protected void registerListeners() {
        ClickUtils.applySingleDebouncing(ivVipBack, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        rvVipRecycler.addOnItemTouchListener(new RecyclerItemClickListener(this, rvVipRecycler, new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                vipAdapter.setSelected(position);
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        }));

        ClickUtils.applySingleDebouncing(tvVipBuy, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initVipOrderCreateLog();
            }
        });
    }

    @Override
    protected void getExtras(Bundle bundle) {

    }

    @Override
    protected boolean isRegisterEventBus() {
        return false;
    }

    @Override
    protected void doAction() {
        initMemberSetting();
    }

    //获取会员信息描述，会员种类
    private void initMemberSetting() {
        EasyHttp.post(this)
                .api(new MemberSettingApi())
                .request(new HttpCallback<HttpData<MemberSettingApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<MemberSettingApi.Bean> result) {
                        if (result != null && result.getData() != null && result.getData().getList().size() > 0) {
                            mBeanInfo = result.getData().getList().get(0);
                            mCurrentLevel = result.getData().getCurrentLevel();
                            vipAdapter.setList(result.getData().getList());
                            setMemberSetting(mBeanInfo);
                        }
                    }
                });
    }

    //订单创建
    private void initVipOrderCreateLog() {
        if (mBeanInfo == null) {
            return;
        }
        if (mBeanInfo.getMoney() <= 0) {
            ToastUtils.showShort("当前为免费会员");
            return;
        }
        EasyHttp.post(this)
                .api(new VipOrderCreateApi().setLevel(mBeanInfo.getLevel()))
                .request(new HttpCallback<HttpData<VipOrderCreateApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<VipOrderCreateApi.Bean> vipResult) {
                        if (vipResult != null && vipResult.getData() != null) {
                            EasyHttp.post(VipActivity.this)
                                    .api(new OrderInfoApi().setPayOrderId(vipResult.getData().getPayOrderId()))
                                    .request(new HttpCallback<HttpData<OrderInfoApi.Bean>>(VipActivity.this) {
                                        @Override
                                        public void onSucceed(HttpData<OrderInfoApi.Bean> orderInfoResult) {
                                            if (orderInfoResult != null && orderInfoResult.getData() != null) {
                                                OrderInfoApi.ChannelBean channelBean = orderInfoResult.getData().getChannelList().get(1);
                                                CashierDialog dialog = CashierDialog.getInstance(VipActivity.this, mBeanInfo.getMoney(), channelBean, new CashierDialog.OnCashierListener() {
                                                    @Override
                                                    public void pay() {
                                                        EasyHttp.post(VipActivity.this)
                                                                .api(new PayParamsApi()
                                                                        .setPayOrderId(vipResult.getData().getPayOrderId())
                                                                        .setChannelId(channelBean.getChannelId()))
                                                                .request(new HttpCallback<HttpData<PayParamsApi.Bean>>(VipActivity.this) {
                                                                    @Override
                                                                    public void onSucceed(HttpData<PayParamsApi.Bean> payParamsResult) {
                                                                        if (payParamsResult != null && payParamsResult.getData() != null) {
//                                                                            IWXAPI api = WXAPIFactory.createWXAPI(mActivity, BaseConfig.WX_APPID, true);
//                                                                            boolean clientValid = api.isWXAppInstalled();
//                                                                            if (clientValid) {
////                                                                                WXPayRequest wxPayRequest = GsonUtils.fromJson(payParamsResult.getData().getWxParams(), WXPayRequest.class);
//                                                                                PayReq request = new PayReq();
//                                                                                request.appId = payParamsResult.getData().getWxParams().getAppId();
//                                                                                request.partnerId = payParamsResult.getData().getWxParams().getPartnerid();
//                                                                                request.prepayId = payParamsResult.getData().getWxParams().getPrepayid();
//                                                                                request.packageValue = payParamsResult.getData().getWxParams().getPackagee();
//                                                                                request.nonceStr = payParamsResult.getData().getWxParams().getNoncestr();
//                                                                                request.timeStamp = payParamsResult.getData().getWxParams().getTimestamp();
//                                                                                request.sign = payParamsResult.getData().getWxParams().getSign();
//                                                                                api.sendReq(request);
//                                                                            } else {
//                                                                                ToastUtils.showShort("请安装微信客户端");
//                                                                            }

                                                                            final String orderInfo = payParamsResult.getData().getAliParams().getOrderStr();   // 订单信息
                                                                            Runnable payRunnable = new Runnable() {
                                                                                @Override
                                                                                public void run() {
                                                                                    PayTask alipay = new PayTask(VipActivity.this);
                                                                                    Map<String, String> result = alipay.payV2(orderInfo, true);
                                                                                    Message msg = new Message();
                                                                                    msg.obj = result;
                                                                                    mHandler.sendMessage(msg);
                                                                                }
                                                                            };
                                                                            // 必须异步调用
                                                                            Thread payThread = new Thread(payRunnable);
                                                                            payThread.start();
                                                                        }
                                                                    }
                                                                });
                                                    }

                                                    @Override
                                                    public void cancel() {

                                                    }
                                                }).builder();
                                                dialog.show();
                                            }
                                        }
                                    });
                        }
                    }
                });
    }

    @Override
    public void onItemSelected(MemberSettingApi.BeanInfo beanInfo) {
        this.mBeanInfo = beanInfo;
        setMemberSetting(beanInfo);
    }

    @SuppressLint("SetTextI18n")
    private void setMemberSetting(MemberSettingApi.BeanInfo beanInfo) {
        if (beanInfo.getDesc().size() >= 1) {
            tvVipTipTileOne.setText(beanInfo.getDesc().get(0).getTitle());
            tvVipTipContentOne.setText(beanInfo.getDesc().get(0).getDescription());

            if (!(beanInfo.getDesc().get(0).getLogo()).isEmpty()){
                Glide.with(this)
                        .asBitmap()
                        .load(CommonConfiguration.splitResUrl(3, beanInfo.getDesc().get(0).getLogo()))
                        .centerInside()
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(new BitmapImageViewTarget(ivVipTipImageOne) {
                            @Override
                            protected void setResource(Bitmap resource) {
                                super.setResource(resource);
                                ivVipTipImageOne.setImageBitmap(ImageUtils.toRoundCorner(resource, 10f));
                            }
                        });
            }
        }

        if (beanInfo.getDesc().size() >= 2) {
            tvVipTipTileTwo.setText(beanInfo.getDesc().get(1).getTitle());
            tvVipTipContentTwo.setText(beanInfo.getDesc().get(1).getDescription());

            if (!(beanInfo.getDesc().get(1).getLogo()).isEmpty()){
                Glide.with(this)
                        .asBitmap()
                        .load(CommonConfiguration.splitResUrl(3, beanInfo.getDesc().get(1).getLogo()))
                        .centerInside()
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(new BitmapImageViewTarget(ivVipTipImageTwo) {
                            @Override
                            protected void setResource(Bitmap resource) {
                                super.setResource(resource);
                                ivVipTipImageTwo.setImageBitmap(ImageUtils.toRoundCorner(resource, 10f));
                            }
                        });
            }
        }

        if (beanInfo.getDesc().size() >= 3) {
            rlVipTipTileThree.setVisibility(View.VISIBLE);
            tvVipTipTileThree.setText(beanInfo.getDesc().get(2).getTitle());
            tvVipTipContentThree.setText(beanInfo.getDesc().get(2).getDescription());
            if (!(beanInfo.getDesc().get(2).getLogo()).isEmpty()){
                Glide.with(this)
                        .asBitmap()
                        .load(CommonConfiguration.splitResUrl(3, beanInfo.getDesc().get(2).getLogo()))
                        .centerInside()
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .into(new BitmapImageViewTarget(ivVipTipImageThree) {
                            @Override
                            protected void setResource(Bitmap resource) {
                                super.setResource(resource);
                                ivVipTipImageThree.setImageBitmap(ImageUtils.toRoundCorner(resource, 10f));
                            }
                        });
            }
        }else {
            rlVipTipTileThree.setVisibility(View.GONE);
        }

        if (beanInfo.getLevel() == mCurrentLevel || beanInfo.getMoney() <= 0) {
            tvVipBuy.setVisibility(View.GONE);
        } else {
            tvVipBuy.setVisibility(View.VISIBLE);
        }
    }
}
